package com.ma.chapter5.t1;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName TPTVolatile
 * @Author: mayongqiang
 * @DATE 2022/3/17 21:00
 * @Description: volatile终止模式-两阶段终止
 */
@Slf4j(topic = "m.TPTVolatile")
public class TPTVolatile {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination1 t = new TwoPhaseTermination1();
        t.start();
        /*某一个线程已经把一件事做好了，无需再做  bulking模式*/
        t.start();
        t.start();
        t.start();
        Thread.sleep(3500);
        log.debug("停止监控");
        t.stop();
    }

}

@Slf4j(topic = "m.TwoPhaseTermination1")
class TwoPhaseTermination1 {
    //监控线程
    private Thread monitorThread;
    //判断是否执行过start()
    private boolean starting = false;
    //保证可见性
    private boolean stop;

    public void start() {
        //保证原子性
        synchronized (this) {
            if (starting) {
                return;
            }
            starting = true;
        }
        monitorThread = new Thread(() -> {
            while (true) {
                Thread thread = Thread.currentThread();
                if (stop) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("执行监控");
                } catch (Exception e) {

                }
            }
        }, "monitor");
        monitorThread.start();
    }

    public void stop() {
        stop = true;
        //希望它尽快退出循环（sleep）
        monitorThread.interrupt();
    }
}
